﻿package Cain.control 
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	/**
	 * Bar控制項
	 * @author Cain
	 */
	public class Bar extends EventDispatcher
	{
		private var bar:DisplayObject;
		private var barModel:BarModel;
		private var top:Number;
		private var foot:Number;
		private var d_y:Number;
		/**
		 * 設定Bar控制項
		 * @param	_bar 控制項物件
		 */
		public function Bar(_bar:DisplayObject) 
		{
			bar = _bar;
		}
		/**
		 * 設定資料
		 * @param	_top 最高點
		 * @param	_foot 最低點
		 * @param	_max 最大數值
		 * @param	_min 最小數值
		 * @param	_now_num 初始值
		 * @param	_num_off 是否用小數
		 */
		public function setup(_top:Number, _foot:Number, _max:Number, _min:Number, _now_num:Number, _num_off:Boolean = false):void
		{
			top = _top;
			foot = _foot;
			barModel = new BarModel(_max, _min, _num_off);
			barModel.setup(_top, _foot, _now_num);
			bar.y = barModel.now;
			play();//移動核心
		}
		//移動核心
		private function play():void
		{
			bar.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down);//bar按下
		}
		//bar按下
		private function mouse_down(e:MouseEvent):void 
		{
			bar.removeEventListener(MouseEvent.MOUSE_DOWN, mouse_down);//移除bar按下
			bar.addEventListener(Event.ENTER_FRAME, bar_enter);//按下後每隔撥放
			d_y = bar.parent.mouseY - bar.y;
		}
		//按下後每隔撥放
		private function bar_enter(e:Event):void 
		{
			bar.stage.addEventListener(MouseEvent.MOUSE_UP, mouse_up);//bar拿起
			var yy:Number = bar.parent.mouseY;
			bar.y = yy-d_y;
			if (bar.y<top) 
			{
				mouse_up();
				bar.y = top;
			}else if(bar.y>foot)
			{
				mouse_up();
				bar.y = foot;
			}
			//連續縮放請打開下面
			now = bar.y;
		}
		//bar拿起
		private function mouse_up(e:MouseEvent = null):void 
		{
			bar.stage.removeEventListener(MouseEvent.MOUSE_UP, mouse_up);//移除bar拿起
			bar.removeEventListener(Event.ENTER_FRAME, bar_enter);//移除按下後每隔撥放
			bar.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down);//bar按下
			//不連續縮放請打開下面
			//now = bar.y;
		}
		/**
		 * 是否作用
		 */
		public function set enable(_en:Boolean):void
		{
			if (_en) 
			{
				bar.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down);//bar按下
			}else 
			{
				bar.removeEventListener(MouseEvent.MOUSE_DOWN, mouse_down);//移除bar按下
			}
		}
		/**
		 * Bar位置
		 */
		public function set now(_now:Number):void
		{
			barModel.now = _now;
			dispatchEvent(new Event(BarModel.CHING));//發出變動事件
		}
		public function get now():Number
		{
			return barModel.now;
		}
		/**
		 * 內容值
		 */
		public function set num(_num:Number):void
		{
			barModel.num = _num;
			bar.y = barModel.now;
			dispatchEvent(new Event(BarModel.CHING));//發出變動事件
		}
		public function get num():Number 
		{
			return barModel.num;
		}
	}

}